const Koa = require('koa')
const app = new Koa()

const views = require('koa-views')
const co = require('co')
const convert = require('koa-convert')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const debug = require('debug')('koa2:server')
const path = require('path')
const session = require('koa-generic-session')
const morgan = require('koa-morgan')
const fs = require('fs')

const config = require('./config/port')
const registerRouter = require('./routes')

const port = process.env.PORT || config.port

// error handler
onerror(app)

// create a write stream
const logFileName = path.join(__dirname, 'logs', 'access.log')
const accessLogStream = fs.createWriteStream(logFileName, { flags: 'a' })
app.use(morgan('combined', { stream: accessLogStream }))

app.keys = ['wxy613ok']
// middlewares
app.use(bodyparser())
  .use(json())
  .use(logger())
  .use(session({
    cookie: {
      path: '/',
      httpOnly: true,
      maxAge: 1000 * 10,
    }
  }))
  .use(registerRouter())

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - $ms`) // 查看当前请求的耗时
})

app.on('error', function(err, ctx) {
  console.log(err)
  logger.error('server error', err, ctx)
})

module.exports = app.listen(config.port, () => {
  console.log(`Listening on http://localhost:${config.port}`)
})
